package com.qipay.admin.utils;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import org.jpos.iso.ISOUtil;

public class DESUtil {

    public static String encode(String target,String apiKey,String inputCharset) throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException, InvalidKeySpecException{
        Cipher cipher = getCipher(Cipher.ENCRYPT_MODE,apiKey,inputCharset);//加密
        return ISOUtil.hexString(cipher.doFinal(target.getBytes()));
    }

    public static String decode(String target,String apiKey,String inputCharset) throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException, InvalidKeySpecException{
        Cipher cipher = getCipher(Cipher.DECRYPT_MODE,apiKey,inputCharset);//解密
        return new String(cipher.doFinal(ISOUtil.hex2byte(target)));
    }

    private static Cipher getCipher(int mode,String apiKey,String inputCharset) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, UnsupportedEncodingException, InvalidKeySpecException {
        DESKeySpec keySpec = new DESKeySpec(getPassword(apiKey,inputCharset));
        Cipher cipher = Cipher.getInstance("DES");
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        cipher.init(mode, keyFactory.generateSecret(keySpec));
        return cipher;
    }

    //密码长度必须是8的倍数
    private static byte[] getPassword(String apiKey,String inputCharset) throws UnsupportedEncodingException {
        return apiKey.getBytes(inputCharset);
    }

}
